package net.ojbk.timeSpace.test.web.handllers.impl;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import net.ojbk.timeSpace.test.beans.APIResult;
import net.ojbk.timeSpace.test.beans.User;
import net.ojbk.timeSpace.test.common.api.APICodeConstant;
import net.ojbk.timeSpace.test.common.sso.InfoClient;
import net.ojbk.timeSpace.test.common.sso.InfoSso;
import net.ojbk.timeSpace.test.web.handllers.IClientController;

@Controller
@RequestMapping("/client")
public class ClientController implements IClientController {

	@Override
	@RequestMapping("client.do")
	@ResponseBody
	public ModelAndView doCilent(String token, HttpSession session) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		RequestConfig rc = RequestConfig.custom().setConnectTimeout(500).setConnectionRequestTimeout(500)
				.setSocketTimeout(500).setRedirectsEnabled(false).build();
		HttpGet httpGet = new HttpGet();
		httpGet.setConfig(rc);

		ModelAndView mv = new ModelAndView();
		mv.setViewName("/index.do");
		
		try {
			httpGet.setURI(new URI(InfoSso.centerLoginUrl + "?" + InfoSso.centerLoginUrlParName1_cname + "="
					+ InfoClient.clientName + "&" + InfoSso.centerLoginUrlParName2_token + "=" + token + "&"
					+ InfoSso.centerLoginUrlParName3_cilentKey + "=" + InfoClient.clientKey));
			CloseableHttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			
			
			
			String str = EntityUtils.toString(entity);
			String code = JSON.parseObject(str).getString("code");
			System.out.println(str);
			response.close();
			httpClient.close();
			if (!code.equals("1")) {
				mv.addObject("msg", "异常....");
				mv.setViewName("/noLoginHome.html");
				return mv;
			}
			// 储存用户信息
			String data = JSON.parseObject(str).getString("data");
			String uid = JSON.parseObject(data).getString("uid");
			System.out.println(uid);
			User user = new User();
			user.setUid(uid);
			session.setAttribute("user", user);
			
			ServletContext sc = session.getServletContext();
			@SuppressWarnings("unchecked")
			Map<String, HttpSession> tokenMap = (Map<String, HttpSession>) sc.getAttribute("tokenMap");
			tokenMap.put(token, session);
			
			return mv;

		} catch (NullPointerException e) {
			// 如果null数据，直接返回即可。
			return mv;
		} catch (IOException e) {
			e.printStackTrace();
			return mv;
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return mv;
		}
	}

	@Override
	@RequestMapping(value="client.do", params={"type", "serviceKey", "token"})
	@ResponseBody
	public Object doClient(String type, String serviceKey, String token, HttpServletRequest  request) {
		if (!type.equals("0")) {
			return null;
		}
		if (!serviceKey.equals(InfoSso.serviceKey) || !request.getRemoteAddr().equals(InfoSso.serviceIp)) {
			return null;
		}
		
		ServletContext sc = request.getServletContext();
		
		@SuppressWarnings("rawtypes")
		Map tokenMap = (Map) sc.getAttribute("tokenMap");
		HttpSession logUserSess = (HttpSession) tokenMap.get(token);
		logUserSess.setAttribute("user", null);
		tokenMap.remove(token);
		System.out.println("loginOut:" + token);
		return APIResult.createSuccessMessage(new APICodeConstant(), "seccess.");
	}

	
	
	@Override
	@RequestMapping("getCId.do")
	@ResponseBody
	public Object doGetCilentId() {
		return APIResult.createSuccess(new APICodeConstant(), InfoClient.clientKey);
	}


}
